import React, { FC ,useEffect,useState} from "react";
import { Pagination } from "antd";
import { LIST_PAGE_PARAM_KEY, LIST_PAGESIZE, LIST_PAGESIZE_PARAM_KEY,List_DEFAULT_PAGE  } from "../constant";
import { useSearchParams } from "react-router-dom";
import { useNavigate,useLocation } from "react-router-dom";
type PropsType = {
    total:number
}

const ListPage: FC<PropsType> = (props: PropsType) => {
    const nav = useNavigate()
    const {pathname}=useLocation()
    const [current, setCurrent] = useState(1)
    const [pageSize,setPageSize]=useState(LIST_PAGESIZE)
    const { total } = props
    const [searchParams] = useSearchParams()
    useEffect(() => {
        const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || "") || List_DEFAULT_PAGE;
        setCurrent(page)
        const pageSize =
          parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || "") ||
            LIST_PAGESIZE;
        setPageSize(pageSize)
    }, [searchParams])
    //
    const HandlePageChange = (page: number, newPageSize: number) => {
        searchParams.set(LIST_PAGE_PARAM_KEY,pageSize!==newPageSize?List_DEFAULT_PAGE.toString():page.toString())
        searchParams.set(LIST_PAGESIZE_PARAM_KEY,newPageSize.toString())
        nav({
            pathname,
            search:searchParams.toString()
        })
    }
  return (
    <div>
          <Pagination showSizeChanger pageSizeOptions={[5,10,20]} current={current} pageSize={pageSize} total={total} onChange={HandlePageChange} />
    </div>
  );
};
export default ListPage;
